package com.wxj.shopping_mall.service.impl;

import com.wxj.shopping_mall.entity.WalletDetails;
import com.wxj.shopping_mall.mapper.WalletDetailsMapper;
import com.wxj.shopping_mall.mapper.WalletMapper;
import com.wxj.shopping_mall.service.WalletDetailsService;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class WalletDetailsServiceImpl implements WalletDetailsService {

    @Autowired
    private WalletDetailsMapper walletDetailsMapper;
    @Autowired
    private WalletMapper walletMapper;

    /**
     * 格式：日期 + 流水
     * 示例：2021012305111300001
     *
     * @return wallet_details_id
     */
    private String generateWalletDetailsID(Integer walletId) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        StringBuilder sb = new StringBuilder();
        String str = UUID.randomUUID().toString().replace("-", "").substring(0, 4);
        sb.append(sdf.format(new Date())).append(str).append(walletId);
        return sb.toString();
    }

    /**
     * 新增交易记录
     *
     * @param walletDetails
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Integer addTransaction(WalletDetails walletDetails, String oldBalance) {
        if (StringUtils.isEmpty(oldBalance)|| ObjectUtils.isEmpty(walletDetails)) return 0;
        Integer walletId = walletDetails.getWalletId();
        BigDecimal amount = walletDetails.getAmount();
        int i = 0;
        // 先更新钱包中的余额
        if (walletDetails.getTransactionMode() == 0) {   // 支出
            i = walletMapper.updateBalance(walletId, amount.negate(), new Date(), oldBalance);
        } else if (walletDetails.getTransactionMode() == 1) {   //转入
            i = walletMapper.updateBalance(walletId, amount, new Date(), oldBalance);
        }
        if (i < 1) return 0;
        // 插入新的钱包流水记录
        walletDetails.setId(generateWalletDetailsID(walletId));
        walletDetails.setCreateDate(new Date());
        return walletDetailsMapper.addTransaction(walletDetails);
    }

    /**
     * 查询用户钱包金额变动明细的接口，按时间降序排列
     *
     * @param walletId
     * @return List<WalletDetails>
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public List<WalletDetails> queryWalletDetails(Integer walletId) {
        return walletDetailsMapper.queryWalletDetails(walletId);
    }
}

